from odoo import models, fields, api, _
from odoo.exceptions import UserError, ValidationError


# 审批流类
class Workflow(models.Model):
    _inherit = 'sb.workflow'

    sale_change_apply_id = fields.Many2one('sale.change.apply', string="Related Documents", ondelete="cascade")
    delink_apply_id = fields.Many2one('delink.apply', string="Related Documents", ondelete="cascade")
    s_erp_lock_id = fields.Many2one('sb.erp.lock', string='erp锁单')
    workflow_type = fields.Selection(selection_add=[
        ('sale_change_apply', 'Sale Change Apply'),
        ('delink_apply', 'Delink Apply'),
        ('lock_erp', 'Lock Erp'),
        ('plan_change_apply', 'Plan Change Apply')
    ], ondelete={'activity': 'cascade'})
    sale_change_apply_ids = fields.One2many('sale.change.apply', 'sb_workflow_id', string='Ecr Apply Lines')
    state = fields.Selection(selection_add=[('return', 'Return')], default="approval", compute="_compute_state", string="Status", store=True)

    # =========ecr==================
    ecr_mo = fields.Many2one('sale.order', related='sale_change_apply_id.sale_order_id',string='MO')
    ecr_apply_type = fields.Selection(related='sale_change_apply_id.apply_type', string='Apply Type')
    ecr_order_type = fields.Selection(related='sale_change_apply_id.order_type', string='Order Change')
    ecr_note = fields.Text(related='sale_change_apply_id.note', string='Change Reason', tracking=True)

    # # 变更前字段 ===================
    o_nre = fields.Float(string='Origin NRE', digits=(16, 3), related="sale_change_apply_id.o_nre")
    o_price_unit = fields.Float('Origin Unit Price', digits='Sale Unit Price', related="sale_change_apply_id.o_price_unit")
    o_po = fields.Char(string="Origin PO", related="sale_change_apply_id.o_po")
    o_note = fields.Html(string='Origin Notes', related="sale_change_apply_id.o_note")
    o_pn = fields.Many2one('customer.item.code', string="Origin PN", related="sale_change_apply_id.o_pn")
    o_pn_code = fields.Char(string="Origin PN", related="sale_change_apply_id.o_pn_code")
    o_qty = fields.Integer(string='Origin Order Qty', related="sale_change_apply_id.o_qty")
    o_commitment_date = fields.Datetime(string='Origin Customer DD', related="sale_change_apply_id.o_commitment_date")
    # o_planned_receiving_date = fields.Datetime(string='Origin Customer DD', related="sale_change_apply_id.o_planned_receiving_date")
    o_version = fields.Char(string="Origin REV", related="sale_change_apply_id.o_version")
    o_pn_desc = fields.Char(string="Origin PN Desc", related="sale_change_apply_id.o_pn_desc")
    o_product_tmpl_id = fields.Many2one('product.template', string='Origin Product', related="sale_change_apply_id.o_product_tmpl_id")
    o_qt = fields.Boolean(string="Origin QTA", related="sale_change_apply_id.o_qt")
    o_materiel_status = fields.Selection([
        ('S', 'NPI'),
        ('P', 'MP'),
        ('T', 'Test'),
        ('Q', 'QTA+NPI'),
    ], string='Origin Product Status', tracking=True, related="sale_change_apply_id.o_materiel_status")
    o_special_order_type = fields.Selection([
        ('eq_only', 'EQ only'),
        ('free_cost', 'Free cost'),
        ('in_stock', 'In stock'),
        ('wb', 'WB'),
        ('prepare_materials', 'Prepare Materials'),
    ], string="Origin Special Order Type", related="sale_change_apply_id.o_special_order_type")
    # ============================

    ###=========可更改的字段===========
    c_nre = fields.Float(string='Target NRE', digits=(16, 3), related="sale_change_apply_id.c_nre")
    c_price_unit = fields.Float('Target Unit Price', digits='Sale Unit Price', related="sale_change_apply_id.c_price_unit")
    c_po = fields.Char(string="Target PO", related="sale_change_apply_id.c_po")
    c_note = fields.Html(string='Target Notes', related="sale_change_apply_id.c_note")
    # c_pn = fields.Many2one('customer.item.code', string="Target PN", related="sale_change_apply_id.c_pn")
    c_pn_code = fields.Char(string="Target PN", related="sale_change_apply_id.c_pn_code")
    c_qty = fields.Integer(string='Target Order Qty', related="sale_change_apply_id.c_qty")
    c_commitment_date = fields.Datetime(string='Target Customer DD', related="sale_change_apply_id.c_commitment_date")
    # c_planned_receiving_date = fields.Datetime(string='Target Customer DD', related="sale_change_apply_id.c_planned_receiving_date")  # 修改成客户交期
    c_version = fields.Char(string="Target REV", related="sale_change_apply_id.c_version")
    c_pn_desc = fields.Char(string="Target PN Desc", related="sale_change_apply_id.c_pn_desc")
    c_product_tmpl_id = fields.Many2one('product.template', string='Target Product', related="sale_change_apply_id.c_product_tmpl_id")
    c_qt = fields.Boolean(string='Target QTA', related="sale_change_apply_id.c_qt")
    c_materiel_status = fields.Selection([
        ('S', 'NPI'),
        ('P', 'MP'),
        ('T', 'Test'),
        ('Q', 'QTA+NPI'),
    ], string='Target Product Status', tracking=True, related="sale_change_apply_id.c_materiel_status")
    c_special_order_type = fields.Selection([
        ('eq_only', 'EQ only'),
        ('free_cost', 'Free cost'),
        ('in_stock', 'In stock'),
        ('wb', 'WB'),
        ('prepare_materials', 'Prepare Materials')
    ], string="Target Special Order Type", related="sale_change_apply_id.c_special_order_type")
    # 判断对应字段是否更改
    is_c_nre = fields.Boolean(default=True, related="sale_change_apply_id.is_c_nre")
    is_c_price_unit = fields.Boolean(default=True, related="sale_change_apply_id.is_c_price_unit")
    is_c_po = fields.Boolean(default=True, related="sale_change_apply_id.is_c_po")
    is_c_note = fields.Boolean(default=True, related="sale_change_apply_id.is_c_note")
    is_c_pn = fields.Boolean(default=True, related="sale_change_apply_id.is_c_pn")
    is_c_qty = fields.Boolean(default=True, related="sale_change_apply_id.is_c_qty")
    # is_c_planned_receiving_date = fields.Boolean(default=True, related="sale_change_apply_id.is_c_planned_receiving_date")
    is_c_version = fields.Boolean(default=True, related="sale_change_apply_id.is_c_version")
    is_c_pn_desc = fields.Boolean(default=True, related="sale_change_apply_id.is_c_pn_desc")
    is_c_product_tmpl_id = fields.Boolean(default=True, related="sale_change_apply_id.is_c_product_tmpl_id")
    is_c_qt = fields.Boolean(default=True, related="sale_change_apply_id.is_c_qt")
    is_c_materiel_status = fields.Boolean(default=True, related="sale_change_apply_id.is_c_materiel_status")
    is_c_special_order_type = fields.Boolean(default=True, related="sale_change_apply_id.is_c_special_order_type")
    is_c_commitment_date = fields.Boolean(default=True, related="sale_change_apply_id.is_c_commitment_date")

    #==============交期修改申请===============
    # 关联交期修改申请
    sb_plan_change_apply_id = fields.Many2one('sb.plan.change.apply', string="Plan Change Apply",
                                                 ondelete="cascade")

    # 获取审批流状态
    @api.depends('sb_workflow_item_ids', 'sb_workflow_item_ids.state')
    def _compute_state(self):
        for workflow in self:
            w_item_states = []
            # 获取全部审批项状态
            for w_item in workflow.sb_workflow_item_ids:
                w_item_states.append(w_item.state)
            # 判断
            if 'no_pass' in w_item_states:
                workflow.state = 'fail_to_approve'
            elif 'approval' in w_item_states or 'wait_forward' in w_item_states:
                workflow.state = 'approval'
            elif 'return' in w_item_states:
                workflow.state = 'return'
            else:
                workflow.state = 'approve'

# 审批流类
class WorkflowItem(models.Model):
    _inherit = 'sb.workflow.item'

    state = fields.Selection(selection_add=[
        ('return', 'Return')
    ], string="Status")

    def review(self):
        rec = super(WorkflowItem, self).review()
        if self.sb_workflow_id.workflow_type == 'sale_change_apply':
            rec['context']['ecr_return'] = True
        return rec
